package com.shwread.android.qysw.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.google.gson.reflect.TypeToken;
import com.shwread.android.qysw10000152.R;
import com.shwread.android.ui.customview.MyListView;
import com.shwread.android.ui.widget.CircleImageView;
import com.shwread.android.ui.widget.CommentView;
import com.shwread.android.ui.widget.refresh.PullToRefreshScrollView;
import com.shwread.android.ui.widget.refresh.PullToRefreshUtil;
import com.shwread.android.ui.widget.refresh.base.PullToRefreshBase;
import com.shwread.android.ui.widget.refresh.base.PullToRefreshBase.OnRefreshListener;
import com.shwread.http.ActionHelp;
import com.shwread.http.base.ObjectHttpResponseHandler;

import org.apache.http.Header;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import logic.bean.CommentBean;
import logic.bean.MeCommentBean;
import logic.constants.Const;
import logic.constants.DefaultConsts;
import logic.util.DateUtil;
import logic.util.ImageLoaderUtil;
import logic.util.Utils;

public class WithMeRelatedActivity
		extends
		BaseBusinessActivity
		implements
		OnClickListener
{

	public static final int       PAGESIZE               = 5;
	private long                  currentPublishTime     = 0;
	private Context mContext;
	private BaseBusinessActivity bActivity;
	private MyListView meRelatedList;
	private MeRelatedAdapter meRelatedAdapter;
	private Button   backBtn,relatedBtn;
	private TextView titleTv;
	private PullToRefreshScrollView withMeScrollView;
	private LinearLayout            withMeNoThing;
	private List<MeCommentBean> meCommentBeans=new ArrayList<MeCommentBean>();
	private boolean hasMore=true;
	String targetType="6";
	String targetValue;
	/************ 评论框 **************/
	private LinearLayout            llayAddComment;
	private CommentView             addCommentView;
	private boolean                 isShowInput  = false;                       // 是否显示输入法


	// 隐藏系统输入法
	InputMethodManager				mInputMethodManager;
	
	@Override
	public Handler getUIHandler() {
		// TODO Auto-generated method stub
		return handler;
	}
	
	Handler handler = new Handler()
	{
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
				case DefaultConsts.COMMENT_SUBMIT_SUCCESS:
					//评论成功
					llayAddComment.setVisibility(View.GONE);
					refresh();
					break;
				case DefaultConsts.COMMENT_SUBMIT_BACK:
					//评论取消
					llayAddComment.setVisibility(View.GONE);
					break;
				
				default:
					break;
			}
		}
    };
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		switch (resultCode) { //resultCode为回传的标记，我在B中回传的是RESULT_OK
		   case RESULT_OK:
		    Bundle b=data.getBundleExtra(BUNDLE_DATA); //data为B中回传的Intent
		    if (data.getExtras().containsKey(BUNDLE_DATA)) {
				refresh();
			}
		    break;
		default:
		    break;
		    }
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.with_me_related);
		getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
		mContext = this;
		bActivity=this;
		initView();
		initData();
		initListener();
	}

	private void initListener() {
		backBtn.setOnClickListener(this);
		withMeScrollView.setOnRefreshListener(new OnRefreshListener<ScrollView>()
		{
			@Override
			public void onRefresh(PullToRefreshBase<ScrollView> refreshView) {
				if (withMeScrollView.isHeaderShown())
				{ // 下拉刷新
					refresh();
				}
				else if (withMeScrollView.isFooterShown())
				{ // 上拉加载
					loadMore();
				}
			}
		});
	}
	
	/** 下拉刷新 */
	private void refresh() {
		currentPublishTime=0;
		meCommentBeans.clear();
		ActionHelp.qryCommentRelateMeList(mContext, currentPublishTime, PAGESIZE, new CommentRelateMeList());
	}
	
	/** 加载更多 */
	private void loadMore() {
		ActionHelp.qryCommentRelateMeList(mContext, currentPublishTime, PAGESIZE, new CommentRelateMeList());
	}

	private void initData() {
		titleTv.setText("与我相关");
		ActionHelp.qryCommentRelateMeList(mContext, currentPublishTime, PAGESIZE, new CommentRelateMeList());
		
	}
	
	private void inData() {
		if (meRelatedAdapter==null) {
			meRelatedAdapter = new MeRelatedAdapter();
			meRelatedList.setAdapter(meRelatedAdapter);	
		}
		else {
			meRelatedAdapter.notifyDataSetChanged();
			withMeScrollView.onRefreshComplete();
		}
	}

	private void initView() {
		meRelatedList = (MyListView) findViewById(R.id.with_me_related_list);
		withMeScrollView = (PullToRefreshScrollView) findViewById(R.id.with_me_related_list_view);
		withMeNoThing = (LinearLayout) findViewById(R.id.with_me_related_huifu_nothing);
		backBtn = (Button) findViewById(R.id.common_header_back);
		backBtn.setVisibility(View.VISIBLE);
		titleTv = (TextView) findViewById(R.id.common_header_name);
		PullToRefreshUtil.initLabel(mContext, withMeScrollView);
		// 评论输入框
		llayAddComment = (LinearLayout) findViewById(R.id.with_me_related_huifu);
		llayAddComment.setVisibility(View.GONE);
		addCommentView = new CommentView(this);
		llayAddComment.addView(addCommentView);
	}

	class MeRelatedAdapter 
			extends
			BaseAdapter
	{
		ViewHolder holder;
		ReplyAdapter replyAdapter;
		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return meCommentBeans.size();
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return meCommentBeans.get(position);
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub
			final MeCommentBean bean=(MeCommentBean) getItem(position);
			if (convertView == null)
			{
				holder = new ViewHolder();
				convertView = LayoutInflater.from(mContext).inflate(R.layout.with_me_related_item, null);
				holder.replyList = (MyListView) convertView.findViewById(R.id.with_me_related_list_item_huifu_list);
				holder.withMePubCiv = (CircleImageView) convertView.findViewById(R.id.with_me_related_list_item_image_1);
				holder.withMeIv = (ImageView) convertView.findViewById(R.id.with_me_related_list_item_image_2);
				holder.withMeName = (TextView) convertView.findViewById(R.id.with_me_related_list_item_name_1);
				holder.withMeTime = (TextView) convertView.findViewById(R.id.with_me_related_list_item_times_1);
				holder.withMeTheme = (TextView) convertView.findViewById(R.id.with_me_related_list_item_text_1);
				holder.withMeConName = (TextView) convertView.findViewById(R.id.with_me_related_list_item_name_2);
				holder.withMeContent = (TextView) convertView.findViewById(R.id.with_me_related_list_item_times_2);
				holder.withMeAssociated = (TextView) convertView.findViewById(R.id.with_my_reply_associated);
				holder.withMeHudongRl = (RelativeLayout) convertView.findViewById(R.id.with_me_related_list_item_hudong_rl);
				convertView.setTag(holder);
			}
			else
			{
				holder = (ViewHolder) convertView.getTag();
			}
			ImageLoaderUtil.loadWebUrl(bean.getCommentUserHeadImage(), holder.withMePubCiv);
			if (Utils.isEmpty(bean.getTopicImgList())) {
				holder.withMeIv.setVisibility(View.GONE);
			}
			else {
				holder.withMeIv.setVisibility(View.VISIBLE);
				String[] str=bean.getTopicImgList().split(",");
				ImageLoaderUtil.loadWebUrl(str[0], holder.withMeIv);				
			}
			holder.withMeName.setText(bean.getCommentUserNickName());
			holder.withMeTime.setText(DateUtil.getRegionTime(bean.getCreateTime()));
			holder.withMeTheme.setText(bean.getContent());
			if ((bean.getAuthorRole()).equals("3"))
			{//系统
				holder.withMeConName.setText("推荐主题:");
			}else {
				holder.withMeConName.setText(bean.getTopicNickName()+":");
			}
			holder.withMeContent.setText(bean.getTopicContent());
			holder.withMeAssociated.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View arg0) {
					// TODO Auto-generated method stub
					if (isShowInput)
					{
						addCommentView.setDefaultHint();
						addCommentView.setCommentParams(bActivity, targetType, targetValue);
						addCommentView.hideInputMethod();
						return;
					}
					addCommentView.setButtonBack(true);
					llayAddComment.setVisibility(View.VISIBLE);
					targetValue=bean.topicId+"";
					if (Const.phone_number.equals(bean.getCommentUserAccount()))
					{
						addCommentView.setDefaultHint();
						addCommentView.setCommentParams(bActivity, targetType, targetValue);
					}
					else
					{
						addCommentView.setHintString(bean.commentUserNickName);
						addCommentView.setReplyParams(bActivity, targetType, targetValue, (long)bean.commentUserId, bean.commentUserAccount, (long)bean.commentId);
					}
					addCommentView.showInputMethod();
				}

			});
			holder.withMeHudongRl.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View arg0) {
					Intent intent = new Intent();
					intent.setClass(mContext, NewInteractionDetailsActivity.class);
					intent.putExtra("MeCommentBean", bean);
					startActivityForResult(intent, BaseBusinessActivity.COMMENTS_REQUEST_CODE);
				}
			});
			if (bean.getCommentList().size()<=1) {
				holder.replyList.setVisibility(View.GONE);
			}
			else {
				holder.replyList.setVisibility(View.VISIBLE);
				replyAdapter = new ReplyAdapter(bean.getCommentList(),bean.getCommentUserAccount());
				holder.replyList.setAdapter(replyAdapter);				
			}
			return convertView;
		}
		
	}
	
	private class ViewHolder
	{
		MyListView replyList;
		CircleImageView withMePubCiv;
		ImageView withMeIv;
		RelativeLayout withMeHudongRl;
		TextView withMeName,withMeTime,withMeTheme,withMeConName,withMeContent,withMeAssociated;
	}
	
	class ReplyAdapter
		extends
		BaseAdapter
	{
		ReplyHolder replyHolder;
		List<CommentBean> commentBeans;
		String commentUserAcc;
		
		public ReplyAdapter(List<CommentBean> commentBeans,String commentUserAcc) {
			this.commentBeans=commentBeans;
			this.commentUserAcc=commentUserAcc;
		}
		
		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			if (commentBeans.get(0).getCommentUserAccount().equals(commentUserAcc)) {//最后一条评论是评论发起人
				return commentBeans.size()-1;
			}
			else {
				return commentBeans.size();
			}
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return commentBeans.get(commentBeans.size()-(1+position));
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			CommentBean bean=(CommentBean) getItem(position);
			if (convertView == null)
			{
				replyHolder = new ReplyHolder();
				convertView = LayoutInflater.from(mContext).inflate(R.layout.with_me_related_list_item_huifu_list_item, null);
				replyHolder.commentUser = (TextView) convertView.findViewById(R.id.with_me_related_list_item_huifu_name_2);
				replyHolder.replyCommentUser = (TextView) convertView.findViewById(R.id.with_me_related_list_item_huifu_name_1);
				replyHolder.content = (TextView) convertView.findViewById(R.id.with_me_related_list_item_huifu_content);
				replyHolder.replySay = (TextView) convertView.findViewById(R.id.with_me_related_list_item_huifu_say);
				convertView.setTag(replyHolder);
			}
			else
			{
				replyHolder = (ReplyHolder) convertView.getTag();
			}
			if (bean.getCommentType()==1) {//直接回复
				replyHolder.commentUser.setText(bean.getCommentUserNickName());
				replyHolder.replyCommentUser.setVisibility(View.GONE);
				replyHolder.replySay.setVisibility(View.GONE);
				replyHolder.content.setText(bean.getContent());
			}else if (bean.getCommentType()==2) {//回复用户
				replyHolder.commentUser.setText(bean.getCommentUserNickName());
				replyHolder.replyCommentUser.setText(bean.getReplyCommentUserNickName());
				replyHolder.replyCommentUser.setVisibility(View.VISIBLE);
				replyHolder.replySay.setVisibility(View.VISIBLE);
				replyHolder.content.setText(bean.getContent());				
			}
			return convertView;
		}
		
	}
	
	class ReplyHolder
	{
		TextView commentUser,replyCommentUser,content,replySay;
	}

	@Override
	public void onClick(View arg0) {
		switch (arg0.getId()) {
		case R.id.common_header_back:
			finish();
			break;

		default:
			break;
		}
		
	}
	
	class CommentRelateMeList
			extends
			ObjectHttpResponseHandler<List<MeCommentBean>>
	{

		@Override
		public Type getType() {
			// TODO Auto-generated method stub
			return new TypeToken<List<MeCommentBean>>(){}.getType();
		}

		@Override
		public void onFailure(int arg0, Header[] arg1, String arg2,
				Throwable arg3) {
			// TODO Auto-generated method stub
//			Utils.showToast(mContext, "****失败****");
		}

		@Override
		public void onSuccess(int arg0, Header[] arg1, List<MeCommentBean> arg2,
				String arg3) {
			// TODO Auto-generated method stub
//			Utils.showToast(mContext, "****成功****");
			if (arg2 == null || arg2.size() == 0)
			{
				//取到的内空为空
				hasMore = false;
				if (currentPublishTime==0) {
					withMeNoThing.setVisibility(View.VISIBLE);
					withMeScrollView.setVisibility(View.GONE);
				}
				withMeScrollView.onRefreshComplete();
			}
			else {
				hasMore=true;
				withMeNoThing.setVisibility(View.GONE);
				withMeScrollView.setVisibility(View.VISIBLE);
				if (currentPublishTime==0) {
					meCommentBeans=arg2;
				}
				else {
					meCommentBeans.addAll(arg2);
				}
				MeCommentBean lastItem = arg2.get(arg2.size() - 1);
				currentPublishTime = lastItem.getCreateTime();
				inData();
			}
		}

	}
}
